package com.jn.zhinongbao.adapter.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.supportingagriculturaltreasures.ChatActivity;
import com.example.supportingagriculturaltreasures.R;
import com.example.supportingagriculturaltreasures.adapter.ChatRoomAdapter;
import com.example.supportingagriculturaltreasures.bean.ChatRoom;
import com.example.supportingagriculturaltreasures.utils.ChatManager;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;

import java.util.List;

/**
 * 消息列表Fragment
 */
public class MessageFragment extends Fragment implements ChatRoomAdapter.OnItemClickListener {

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private TextView tvEmpty;
    
    private ChatRoomAdapter adapter;
    private ChatManager chatManager;
    private PreferenceManager preferenceManager;
    private int currentUserId;

    public MessageFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        chatManager = ChatManager.getInstance(getContext());
        preferenceManager = new PreferenceManager(getContext());
        currentUserId = preferenceManager.getCurrentUserId();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_message, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initViews(view);
        setupRecyclerView();
        loadChatRooms();
    }

    private void initViews(View view) {
        recyclerView = view.findViewById(R.id.recycler_view);
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        tvEmpty = view.findViewById(R.id.tv_empty);

        // 设置下拉刷新
        swipeRefreshLayout.setOnRefreshListener(this::loadChatRooms);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright);
    }

    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new ChatRoomAdapter(getContext(), null, currentUserId);
        adapter.setOnItemClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    private void loadChatRooms() {
        if (currentUserId == -1) {
            Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
            swipeRefreshLayout.setRefreshing(false);
            return;
        }

        // 获取聊天室列表
        List<ChatRoom> chatRooms = chatManager.getChatRoomList(currentUserId);
        
        if (chatRooms.isEmpty()) {
            showEmptyView();
        } else {
            hideEmptyView();
            adapter.updateData(chatRooms);
        }

        swipeRefreshLayout.setRefreshing(false);
    }

    private void showEmptyView() {
        recyclerView.setVisibility(View.GONE);
        tvEmpty.setVisibility(View.VISIBLE);
    }

    private void hideEmptyView() {
        recyclerView.setVisibility(View.VISIBLE);
        tvEmpty.setVisibility(View.GONE);
    }

    @Override
    public void onItemClick(ChatRoom chatRoom) {
        // 点击聊天室，进入聊天界面
        Intent intent = new Intent(getContext(), ChatActivity.class);
        intent.putExtra("chat_room_id", chatRoom.getId());
        intent.putExtra("other_user_name", chatRoom.getOtherUserName(currentUserId));
        intent.putExtra("other_user_id", chatRoom.getOtherUserId(currentUserId));
        startActivity(intent);
    }

    @Override
    public void onItemLongClick(ChatRoom chatRoom) {
        // 长按显示操作菜单
        showChatRoomOptionsDialog(chatRoom);
    }

    private void showChatRoomOptionsDialog(ChatRoom chatRoom) {
        String[] options = {"删除聊天", "清空聊天记录"};
        
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("选择操作")
                .setItems(options, (dialog, which) -> {
                    switch (which) {
                        case 0:
                            // 删除聊天
                            deleteChatRoom(chatRoom);
                            break;
                        case 1:
                            // 清空聊天记录
                            clearChatMessages(chatRoom);
                            break;
                    }
                })
                .show();
    }

    private void deleteChatRoom(ChatRoom chatRoom) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("删除聊天")
                .setMessage("确定要删除与 " + chatRoom.getOtherUserName(currentUserId) + " 的聊天吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    chatManager.deleteChatRoom(chatRoom.getId());
                    loadChatRooms();
                    Toast.makeText(getContext(), "聊天已删除", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void clearChatMessages(ChatRoom chatRoom) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("清空聊天记录")
                .setMessage("确定要清空与 " + chatRoom.getOtherUserName(currentUserId) + " 的聊天记录吗？")
                .setPositiveButton("清空", (dialog, which) -> {
                    // TODO: 实现清空聊天记录功能
                    Toast.makeText(getContext(), "聊天记录已清空", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    public void onResume() {
        super.onResume();
        // 重新加载聊天室列表，以更新未读消息等状态
        loadChatRooms();
    }

    /**
     * 刷新聊天室列表（供外部调用）
     */
    public void refreshChatRooms() {
        if (isAdded() && !isDetached()) {
            loadChatRooms();
        }
    }
} 